from flask import Blueprint,request,make_response,redirect,jsonify
from application.models.users.user import User,db
from utils.captcha.captcha import captcha
from utils.myredis import r
import redis
from utils.send_code import send_message

import json


user_blue = Blueprint("userblue",__name__)

@user_blue.route("/img")
def reg():
    name,text,image=captcha.generate_captcha()
    uuid=request.args.get("picuuid")
    print("uuid??/?",uuid)
    r.str_add(uuid,str(text),90)
    res=make_response(image)
    res.headers['Content-Type']="image/jpg"
    return res

import random
@user_blue.route("/send",methods=['POST'])
def send():
    data=json.loads(request.data)
    if data:
        uuid=data['picuuid']
        piccode=data['piccode']
        mobile=data['mobile']
        value=r.str_get(uuid)
        if value:
            if piccode.lower() == value.lower().decode():
                mcode=r.str_get(mobile)
                if mcode:
                    return jsonify({"code":10012,"msg":"一分钟只能发送一次"})
                scode=random.randint(10000,99999)
                flag=send_message(mobile,scode)
                print("flag?????????",flag)

                res=r.str_add(mobile, scode, 90)
                print("res??????",res)

                # 删除图片验证码
                r.del_key(uuid)
                return jsonify({"code":200,"msg":"发送成功"})

            else:
                return jsonify({"code":10017,"msg":"图片验证码错误"})
        else:
            return jsonify({"code":10010,"msg":"图片验证码不存在"})

from utils.myjwt import myjwt
@user_blue.route("/login",methods=['POST'])
def login():
    # 获取手机号、验证码参数
    data=request.data
    if data:
        data=json.loads(data)
        # 获取两个参数
        mcode=data['code']
        mobile=data['mobile']
        # 根据手机号去redis中获取验证码
        code=r.str_get(mobile)
        if code:
            if int(mcode)==int(code):
                # 如果相同查询数据库user表
                u = User.query.filter_by(mobile=mobile).first()
                print("uuuu",u)
                if u:
                    r.del_key(mobile)
                    # return jsonify({"code":402,"msg":"该用户已存在"})

                else:
                    u = User(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                data = {'data': {'userid': u['id']}}
                token = myjwt.jwt_encode(data)
                return jsonify({"code":200,"token":token,"userid":u.id})
            else:
                return jsonify({"code":10044,"msg":"验证码错误"})
        else:
            return jsonify({"code":1004,"msg":"没有获取到参数"})





